/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ipfw.cs590.cheat.struts.actions;

import edu.ipfw.cs590.cheat.AssignmentManagementInterface;
import edu.ipfw.cs590.cheat.AssignmentManagementService;
import edu.ipfw.cs590.cheat.util.Authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author jmbaker
 */
public class LogoutAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private final static String SUCCESS = "LogoutSuccess";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //Destroy session variables
        HttpSession session = request.getSession(false);

        if (session != null) {
            try {
                //Get the token
                String token = (String) session.getAttribute(Authentication.SESSION_NAME_TOKEN);

                //If the token isn't null log out call
                if (token != null) {
                    // Call Web Service Operation
                    AssignmentManagementService service = new AssignmentManagementService();
                    AssignmentManagementInterface port = service.getAssignmentManagementSOAP();
                    port.logout(new edu.ipfw.cs590.cheat.Logout(), token);
                }
            } catch (Exception exc) {
                ActionMessages errors = new ActionMessages();
                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.service.error", "Logout Service", exc.getMessage()));
                this.saveErrors(request, errors);
            } finally {
                try {
                    //Kill the session
                    session.invalidate();
                } catch (Exception exc) {
                }
            }
        }
        //Store message for redisplay
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE,
                new ActionMessage("success.service.logout"));
        this.saveMessages(request, errors);

        return mapping.findForward(SUCCESS);
    }
}
